﻿
using System.Text.Json;
using System.Text.Json.Nodes;
using Flurl.Http;

namespace RsCms.Infrastructure
{
    public class WebsocketHelper
    {
        public static async Task ConnectServerAsync()
        {
            try
            {
                string url = "https://api.rs888.net/api/ws/pre-connect";

                var ret = await url
                        .WithHeader("Content-Type", "application/json")
                        .PostJsonAsync(new
                        {
                            websocketId = ""
                        });
                var res = await ret.GetStringAsync();

                var json = JsonNode.Parse(res);
                var server = json["result"]["server"];
                WebsocketId = json["result"]["websocketId"]?.ToString();
            }
            catch (Exception e)
            {

            }

        }

        public static string WebsocketId { get; set; } = "";


        public static async Task<string> SendMsgAsync(string accessToken, string receiveWebsocketId, string type, object msg)
        {
            string url = "https://api.rs888.net/api/ws/send/msg";
            var data = new
            {
                senderWebsocketId = WebsocketId,
                receiveWebsocketId = receiveWebsocketId,
                message = JsonSerializer.Serialize(msg),
                type = type
            };
            var ret = await url
                .WithHeader("Authorization", $"Bearer {accessToken}").PostJsonAsync(data);
            return await ret.GetStringAsync();
        }

    }
}
